package ai.people.platform.jx.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import javax.net.ssl.SSLContext;

/**
 * @author LiGuanNan
 * @date 2022/6/29 10:13
 */
@Configuration
public class SpringElasticSearchConfiguration extends AbstractElasticsearchConfiguration {

    @Value("${spring.elasticsearch.rest.uris}")
    private String defaultUris;

    @Value("${spring.elasticsearch.rest.tw.uris}")
    private String twUris;

    @Value("${spring.elasticsearch.rest.fl.uris}")
    private String fbUris;
    @Value("${spring.elasticsearch.rest.fl.username}")
    private String fbUsername;
    @Value("${spring.elasticsearch.rest.fl.password}")
    private String fbPassword;

    @Value("${spring.elasticsearch.rest.connectTimeout}")
    private Integer connectTimeout;
    @Value("${spring.elasticsearch.rest.socketTimeout}")
    private Integer socketTimeout;

    /**
     * 默认的elasticsearch客户（内部es）
     *
     * @return {@link RestHighLevelClient}
     */
    @Override
    public RestHighLevelClient elasticsearchClient() {
        RestClientBuilder builder = RestClient.builder(HttpHost.create(defaultUris))
                .setRequestConfigCallback(config -> {
                    config.setConnectTimeout(connectTimeout);
                    config.setSocketTimeout(socketTimeout);
                    return config;
                });
        //保活策略
        builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                .setDefaultIOReactorConfig(IOReactorConfig.custom()
                        .setSoKeepAlive(true)
                        .build()));
        return new RestHighLevelClient(builder);
    }

    /**
     * 默认的elasticsearchTemplate
     *
     * @return {@link ElasticsearchRestTemplate}
     */
    @Primary
    @Bean("elasticsearchRestTemplate")
    public ElasticsearchRestTemplate elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }

    /**
     * fb elasticsearch客户（fb es）
     *
     * @return {@link RestHighLevelClient}
     */
    public RestHighLevelClient flElasticsearchClient() {
        RestClientBuilder builder = RestClient.builder(HttpHost.create(fbUris))
                .setRequestConfigCallback(config -> {
                    config.setConnectTimeout(connectTimeout);
                    config.setSocketTimeout(socketTimeout);
                    return config;
                });
        // 设置认证信息
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(fbUsername, fbPassword));

        //设置httpClient
        builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
            httpAsyncClientBuilder
                    .disableAuthCaching()
                    .setDefaultIOReactorConfig(IOReactorConfig.custom()
                            .setSoKeepAlive(true)
                            .build())
                    .setSSLContext(getSSLContext());
            return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        });
        return new RestHighLevelClient(builder);
    }

    /**
     * 忽略https证书的SSLContext
     * @return
     */
    private SSLContext getSSLContext() {
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sslContext;
    }

    /**
     * fb ElasticsearchRestTemplate
     *
     * @return {@link ElasticsearchRestTemplate}
     */
    @Bean("flElasticsearchRestTemplate")
    public ElasticsearchRestTemplate flElasticsearchRestTemplate() {
        return new ElasticsearchRestTemplate(flElasticsearchClient());
    }
}
